/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package com.github.sundeepk.compactcalendarview.lib;


import com.github.sundeepk.compactcalendarview.lib.animation.AnimationUtils;
import com.github.sundeepk.compactcalendarview.lib.animation.Interpolator;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.math.BigDecimal;

/**
 * <p>This class encapsulates scrolling. You can use scrollers ({@link Scroller}
 * to collect the data you need to produce a scrolling
 * animation&mdash;for example, in response to a fling gesture. Scrollers track
 * scroll offsets for you over time, but they don't automatically apply those
 * positions to your view. It's your responsibility to get and apply new
 * coordinates at a rate that will make the scrolling animation look smooth.</p>
 *
 * <p>To track the changing positions of the x/y coordinates, use
 * {@link #computeScrollOffset}. The method returns a boolean to indicate
 * whether the scroller is finished. If it isn't, it means that a fling or
 * programmatic pan operation is still in progress. You can use this method to
 * find the current offsets of the x and y coordinates, for example:</p>
 *
 * @since 2021/07/05
 */
public class Scroller {
    private final Interpolator mInterpolator;

    private int mMode;

    private int mStartX;
    private int mStartY;
    private int mFinalX;
    private int mFinalY;

    private int mMinX;
    private int mMaxX;
    private int mMinY;
    private int mMaxY;

    private int mCurrX;
    private int mCurrY;
    private long mStartTime;
    private int mDuration;
    private float mDurationReciprocal;
    private float mDeltaX;
    private float mDeltaY;
    private boolean mFinished;
    private boolean mFlywheel;

    private double mVelocity;
    private double mCurrVelocity;
    private int mDistance;

    private float mFlingFriction = Configuration.getScrollFriction();

    private static final int DEFAULT_DURATION = 250;
    private static final int SCROLL_MODE = 0;
    private static final int FLING_MODE = 1;

    private static final float DECELERATION_RATE = (float) (Math.log(0.78) / Math.log(0.9));
    private static final float INFLEXION = 0.35f; // Tension lines cross at (INFLEXION, 1)
    private static final float START_TENSION = 0.5f;
    private static final float END_TENSION = 1.0f;
    private static final float P1 = START_TENSION * INFLEXION;
    private static final float P2 = 1.0f - END_TENSION * (1.0f - INFLEXION);

    private static final int NB_SAMPLES = 100;
    private static final double[] SPLINE_POSITION = new double[NB_SAMPLES + 1];
    private static final double[] SPLINE_TIME = new double[NB_SAMPLES + 1];

    private float mDeceleration;
    private final float mPpi;

    // A context-specific coefficient adjusted to physical values.
    private final float mPhysicalCoeff;

    static {
        double xMin = 0.0f;
        double yMin = 0.0f;
        for (int i = 0; i < NB_SAMPLES; i++) {
            final double alpha = (double) i / NB_SAMPLES;

            double xMax = 1.0f;
            double xP;
            double tX;
            double coeF;
            while (true) {
                xP = xMin + (xMax - xMin) / 2.0f;
                coeF = 3.0f * xP * (1.0f - xP);
                tX = coeF * ((1.0f - xP) * P1 + xP * P2) + xP * xP * xP;
                if (Math.abs(tX - alpha) < 1E-5) {
                    break;
                }
                if (tX > alpha) {
                    xMax = xP;
                } else {
                    xMin = xP;
                }
            }
            SPLINE_POSITION[i] = coeF * ((1.0f - xP) * START_TENSION + xP) + xP * xP * xP;

            double yMax = 1.0f;
            double yP;
            double dY;
            while (true) {
                yP = yMin + (yMax - yMin) / 2.0f;
                coeF = 3.0f * yP * (1.0f - yP);
                dY = coeF * ((1.0f - yP) * START_TENSION + yP) + yP * yP * yP;
                if (Math.abs(dY - alpha) < 1E-5) {
                    break;
                }
                if (dY > alpha) {
                    yMax = yP;
                } else {
                    yMin = yP;
                }
            }
            SPLINE_TIME[i] = coeF * ((1.0f - yP) * P1 + yP * P2) + yP * yP * yP;
        }
        SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] = 1.0f;
    }

    /**
     * Create a Scroller with the default duration and interpolator.
     *
     * @param context context
     */
    public Scroller(Context context) {
        this(context, null);
    }

    /**
     * Create a Scroller with the specified interpolator. If the interpolator is
     * null, the default (viscous) interpolator will be used. "Flywheel" behavior will
     * be in effect for apps targeting Honeycomb or newer.
     *
     * @param context      context
     * @param interpolator interpolator
     */
    public Scroller(Context context, Interpolator interpolator) {
        this(context, interpolator, true);
    }

    /**
     * Create a Scroller with the specified interpolator. If the interpolator is
     * null, the default (viscous) interpolator will be used. Specify whether or
     * not to support progressive "flywheel" behavior in flinging.
     *
     * @param context      context
     * @param interpolator interpolator
     * @param flywheel     is flywheel
     */
    public Scroller(Context context, Interpolator interpolator, boolean flywheel) {
        mFinished = true;
        if (interpolator == null) {
            mInterpolator = new ViscousFluidInterpolator();
        } else {
            mInterpolator = interpolator;
        }
        mPpi = DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes().densityPixels * 160.0f;
        mDeceleration = computeDeceleration(Configuration.getScrollFriction());
        mFlywheel = flywheel;

        mPhysicalCoeff = computeDeceleration(0.84f); // look and feel tuning
    }

    /**
     * The amount of friction applied to flings. The default value
     * is {@link Configuration#getScrollFriction}.
     *
     * @param friction A scalar dimension-less value representing the coefficient of
     *                 friction.
     */
    public final void setFriction(float friction) {
        mDeceleration = computeDeceleration(friction);
        mFlingFriction = friction;
    }

    private float computeDeceleration(float friction) {
        return Configuration.GRAVITY_EARTH
                * 39.37f
                * mPpi
                * friction;
    }

    /**
     * Returns whether the scroller has finished scrolling.
     *
     * @return True if the scroller has finished scrolling, false otherwise.
     */
    public final boolean isFinished() {
        return mFinished;
    }

    /**
     * Force the finished field to a particular value.
     *
     * @param finished The new finished value.
     */
    public final void forceFinished(boolean finished) {
        mFinished = finished;
    }

    /**
     * Returns how long the scroll event will take, in milliseconds.
     *
     * @return The duration of the scroll in milliseconds.
     */
    public final int getDuration() {
        return mDuration;
    }

    /**
     * Returns the current X offset in the scroll.
     *
     * @return The new X offset as an absolute distance from the origin.
     */
    public final int getCurrX() {
        return mCurrX;
    }

    /**
     * Returns the current Y offset in the scroll.
     *
     * @return The new Y offset as an absolute distance from the origin.
     */
    public final int getCurrY() {
        return mCurrY;
    }

    /**
     * Returns the current velocity.
     *
     * @return The original velocity less the deceleration. Result may be
     * negative.
     */
    public float getCurrVelocity() {
        BigDecimal decimal = BigDecimal.valueOf(mVelocity).subtract(
                BigDecimal.valueOf(mDeceleration).multiply(
                        BigDecimal.valueOf(timePassed()).divide(
                                BigDecimal.valueOf(2000.0f), 5, BigDecimal.ROUND_HALF_UP)));
        return mMode == FLING_MODE ?
                (float) mCurrVelocity : decimal.floatValue();
    }

    /**
     * Returns the start X offset in the scroll.
     *
     * @return The start X offset as an absolute distance from the origin.
     */
    public final int getStartX() {
        return mStartX;
    }

    /**
     * Returns the start Y offset in the scroll.
     *
     * @return The start Y offset as an absolute distance from the origin.
     */
    public final int getStartY() {
        return mStartY;
    }

    /**
     * Returns where the scroll will end. Valid only for "fling" scrolls.
     *
     * @return The final X offset as an absolute distance from the origin.
     */
    public final int getFinalX() {
        return mFinalX;
    }

    /**
     * Returns where the scroll will end. Valid only for "fling" scrolls.
     *
     * @return The final Y offset as an absolute distance from the origin.
     */
    public final int getFinalY() {
        return mFinalY;
    }

    /**
     * Call this when you want to know the new location.  If it returns true,
     * the animation is not yet finished.
     *
     * @return the result
     */
    public boolean computeScrollOffset() {
        if (mFinished) {
            return false;
        }

        int timePassed = (int) (AnimationUtils.currentAnimationTimeMillis() - mStartTime);

        if (timePassed < mDuration) {
            switch (mMode) {
                case SCROLL_MODE:
                    final float xP = mInterpolator.getInterpolation(timePassed * mDurationReciprocal);
                    mCurrX = mStartX + Math.round(xP * mDeltaX);
                    mCurrY = mStartY + Math.round(xP * mDeltaY);
                    break;
                case FLING_MODE:
                    final double basicT = (float) timePassed / mDuration;
                    final int index = (int) (NB_SAMPLES * basicT);
                    double distanceCoeF = 1.f;
                    double velocityCoeF = 0.f;
                    if (index < NB_SAMPLES) {
                        final double tInf = (float) index / NB_SAMPLES;
                        final double tSup = (float) (index + 1) / NB_SAMPLES;
                        final double dInf = SPLINE_POSITION[index];
                        final double dSup = SPLINE_POSITION[index + 1];
                        velocityCoeF = (dSup - dInf) / (tSup - tInf);
                        distanceCoeF = dInf + (basicT - tInf) * velocityCoeF;
                    }

                    mCurrVelocity = velocityCoeF * mDistance / mDuration * 1000.0f;

                    mCurrX = mStartX + (int) Math.round(distanceCoeF * (mFinalX - mStartX));
                    // Pin to mMinX <= mCurrX <= mMaxX
                    mCurrX = Math.min(mCurrX, mMaxX);
                    mCurrX = Math.max(mCurrX, mMinX);

                    mCurrY = mStartY + (int) Math.round(distanceCoeF * (mFinalY - mStartY));
                    // Pin to mMinY <= mCurrY <= mMaxY
                    mCurrY = Math.min(mCurrY, mMaxY);
                    mCurrY = Math.max(mCurrY, mMinY);

                    if (mCurrX == mFinalX && mCurrY == mFinalY) {
                        mFinished = true;
                    }

                    break;
            }
        } else {
            mCurrX = mFinalX;
            mCurrY = mFinalY;
            mFinished = true;
        }
        return true;
    }

    /**
     * Start scrolling by providing a starting point and the distance to travel.
     * The scroll will use the default value of 250 milliseconds for the
     * duration.
     *
     * @param startX Starting horizontal scroll offset in pixels. Positive
     *               numbers will scroll the content to the left.
     * @param startY Starting vertical scroll offset in pixels. Positive numbers
     *               will scroll the content up.
     * @param dx     Horizontal distance to travel. Positive numbers will scroll the
     *               content to the left.
     * @param dy     Vertical distance to travel. Positive numbers will scroll the
     *               content up.
     */
    public void startScroll(int startX, int startY, int dx, int dy) {
        startScroll(startX, startY, dx, dy, DEFAULT_DURATION);
    }

    /**
     * Start scrolling by providing a starting point, the distance to travel,
     * and the duration of the scroll.
     *
     * @param startX   Starting horizontal scroll offset in pixels. Positive
     *                 numbers will scroll the content to the left.
     * @param startY   Starting vertical scroll offset in pixels. Positive numbers
     *                 will scroll the content up.
     * @param dx       Horizontal distance to travel. Positive numbers will scroll the
     *                 content to the left.
     * @param dy       Vertical distance to travel. Positive numbers will scroll the
     *                 content up.
     * @param duration Duration of the scroll in milliseconds.
     */
    public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        mMode = SCROLL_MODE;
        mFinished = false;
        mDuration = duration;
        mStartTime = AnimationUtils.currentAnimationTimeMillis();
        mStartX = startX;
        mStartY = startY;
        mFinalX = startX + dx;
        mFinalY = startY + dy;
        mDeltaX = dx;
        mDeltaY = dy;
        mDurationReciprocal = 1.0f / (float) mDuration;
    }

    /**
     * Start scrolling based on a fling gesture. The distance travelled will
     * depend on the initial velocity of the fling.
     *
     * @param pointBean pointBean
     */
    public void fling(PointBean pointBean) {
        // Continue a scroll or fling in progress
        int basicVelocityX = pointBean.getVelocityX();
        int basicVelocityY = pointBean.getVelocityY();
        if (mFlywheel && !mFinished) {
            double oldVel = getCurrVelocity();

            double dx = (float) (mFinalX - mStartX);
            double dy = (float) (mFinalY - mStartY);
            double hyp = (float) Math.hypot(dx, dy);

            double ndx = dx / hyp;
            double ndy = dy / hyp;

            double oldVelocityX = ndx * oldVel;
            double oldVelocityY = ndy * oldVel;
            if (Math.signum(oldVelocityX) == Math.signum(oldVelocityX) &&
                    Math.signum(oldVelocityY) == Math.signum(oldVelocityY)) {
                basicVelocityX += oldVelocityX;
                basicVelocityY += oldVelocityY;
            }
        }

        mMode = FLING_MODE;
        mFinished = false;

        double velocity = (float) Math.hypot(basicVelocityX, basicVelocityY);

        mVelocity = velocity;
        mDuration = getSplineFlingDuration((float) velocity);
        mStartTime = AnimationUtils.currentAnimationTimeMillis();
        mStartX = pointBean.getStartX();
        mStartY = pointBean.getStartY();

        double totalDistance = getSplineFlingDistance((float) velocity);
        mDistance = (int) (totalDistance * Math.signum(velocity));

        mMinX = pointBean.getMinX();
        mMaxX = pointBean.getMaxX();
        mMinY = pointBean.getMinY();
        mMaxY = pointBean.getMaxY();
        double coeffX = velocity == 0 ? 1.0f : basicVelocityX / velocity;

        mFinalX = pointBean.getMaxX() + (int) Math.round(totalDistance * coeffX);
        // Pin to mMinX <= mFinalX <= mMaxX
        mFinalX = Math.min(mFinalX, mMaxX);
        mFinalX = Math.max(mFinalX, mMinX);
        double coeffY = velocity == 0 ? 1.0f : basicVelocityY / velocity;

        mFinalY = pointBean.getMaxY() + (int) Math.round(totalDistance * coeffY);
        // Pin to mMinY <= mFinalY <= mMaxY
        mFinalY = Math.min(mFinalY, mMaxY);
        mFinalY = Math.max(mFinalY, mMinY);
    }

    private double getSplineDeceleration(float velocity) {
        return Math.log(INFLEXION * Math.abs(velocity) / (mFlingFriction * mPhysicalCoeff));
    }

    private int getSplineFlingDuration(float velocity) {
        final double basicL = getSplineDeceleration(velocity);
        final double decelMinusOne = DECELERATION_RATE - 1.0;
        return (int) (1000.0 * Math.exp(basicL / decelMinusOne));
    }

    private double getSplineFlingDistance(float velocity) {
        final double basicL = getSplineDeceleration(velocity);
        final double decelMinusOne = DECELERATION_RATE - 1.0;
        return mFlingFriction * mPhysicalCoeff * Math.exp(DECELERATION_RATE / decelMinusOne * basicL);
    }

    /**
     * Stops the animation. Contrary to {@link #forceFinished(boolean)},
     * aborting the animating cause the scroller to move to the final x and y
     * position
     *
     * @see #forceFinished(boolean)
     */
    public void abortAnimation() {
        mCurrX = mFinalX;
        mCurrY = mFinalY;
        mFinished = true;
    }

    /**
     * Extend the scroll animation. This allows a running animation to scroll
     * further and longer, when used with {@link #setFinalX(int)} or {@link #setFinalY(int)}.
     *
     * @param extend Additional time to scroll in milliseconds.
     * @see #setFinalX(int)
     * @see #setFinalY(int)
     */
    public void extendDuration(int extend) {
        int passed = timePassed();
        mDuration = passed + extend;
        mDurationReciprocal = 1.0f / mDuration;
        mFinished = false;
    }

    /**
     * Returns the time elapsed since the beginning of the scrolling.
     *
     * @return The elapsed time in milliseconds.
     */
    public int timePassed() {
        return (int) (AnimationUtils.currentAnimationTimeMillis() - mStartTime);
    }

    /**
     * Sets the final position (X) for this scroller.
     *
     * @param newX The new X offset as an absolute distance from the origin.
     * @see #extendDuration(int)
     * @see #setFinalY(int)
     */
    public void setFinalX(int newX) {
        mFinalX = newX;
        mDeltaX = mFinalX - mStartX;
        mFinished = false;
    }

    /**
     * Sets the final position (Y) for this scroller.
     *
     * @param newY The new Y offset as an absolute distance from the origin.
     * @see #extendDuration(int)
     * @see #setFinalX(int)
     */
    public void setFinalY(int newY) {
        mFinalY = newY;
        mDeltaY = mFinalY - mStartY;
        mFinished = false;
    }

    /**
     * isScrollingInDirection
     *
     * @param xVel xVel
     * @param yVel yVel
     * @return boolean
     */
    public boolean isScrollingInDirection(float xVel, float yVel) {
        return !mFinished && Math.signum(xVel) == Math.signum(mFinalX - mStartX) &&
                Math.signum(yVel) == Math.signum(mFinalY - mStartY);
    }

    static class ViscousFluidInterpolator implements Interpolator {
        /**
         * Controls the viscous fluid effect (how much of it).
         */
        private static final double VISCOUS_FLUID_SCALE = 8.0f;

        private static final double VISCOUS_FLUID_NORMALIZE;
        private static final double VISCOUS_FLUID_OFFSET;

        static {

            // must be set to 1.0 (used in viscousFluid())
            VISCOUS_FLUID_NORMALIZE = 1.0f / viscousFluid(1.0f);
            // account for very small floating-point error
            VISCOUS_FLUID_OFFSET = 1.0f - VISCOUS_FLUID_NORMALIZE * viscousFluid(1.0f);
        }

        private static double viscousFluid(double xPosition) {
            double basicX = xPosition;
            basicX *= VISCOUS_FLUID_SCALE;
            if (basicX < 1.0f) {
                basicX -= (1.0F - Math.exp(-xPosition));
            } else {
                double start = 0.36787944117F;   // 1/e == exp(-1)
                basicX = 1.0f - Math.exp(1.0F - basicX);
                basicX = start + basicX * (1.0F - start);
            }
            xPosition = basicX;
            return xPosition;
        }

        @Override
        public float getInterpolation(float input) {
            final double interpolated = VISCOUS_FLUID_NORMALIZE * viscousFluid(input);
            if (interpolated > 0) {
                return (float) (interpolated + VISCOUS_FLUID_OFFSET);
            }
            return (float) interpolated;
        }
    }
}

